package com.landeb.shop.huo.act;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.Json2Act;
import com.landeb.shop.huo.MyApplication;

public class Html5Activity extends BaseActivity implements View.OnClickListener {

    private String mUrl;
    private String title;
    private String token;
    private String mUrlWithToken;

    public static final String TITLE = "title";
    public static final String URL = "url";

    private Button btnBackward, btnRefresh, btnForward;
    private LinearLayout btnBack;
    private TextView mTitle;
    private WebView mWebView;

    public static void toAct(Context context, String title, String url) {
        Intent intent = new Intent(context, Html5Activity.class);
        intent.putExtra(TITLE, title);
        intent.putExtra(URL, url);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_html5);

        Intent intent = getIntent();
        title = intent.getStringExtra(TITLE);
        mUrl = intent.getStringExtra(URL);

        Log.d("Url:", mUrl);

//        Toast.makeText(this,mUrl,Toast.LENGTH_SHORT).show();

        initView();
        initData();
        initEvent();


    }

    private void initEvent() {

        btnBack.setOnClickListener(this);
        btnBackward.setOnClickListener(this);
        btnRefresh.setOnClickListener(this);
        btnForward.setOnClickListener(this);

        WebSettings mWebSettings = mWebView.getSettings();
        mWebSettings.setUserAgentString("android/app/landeb1.0");//添加UA,  “app/XXX”：是与h5商量好的标识，h5确认UA为app/XXX就认为该请求的终端为App

        mWebSettings.setSupportZoom(true);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setDefaultTextEncodingName("utf-8");
        mWebSettings.setLoadsImagesAutomatically(true);

        //调用JS方法.安卓版本大于17,加上注解 @JavascriptInterface
        mWebSettings.setJavaScriptEnabled(true);

        saveData(mWebSettings);

        newWin(mWebSettings);

        mWebView.setWebChromeClient(webChromeClient);
        mWebView.setWebViewClient(webViewClient);

        mWebView.loadUrl(mUrlWithToken);

        Log.e("trueURL: ", mUrlWithToken);

//        js调用本地方法
        mWebView.addJavascriptInterface(this, "hook_app");
    }

    private void initData() {

        SharedPreferences mPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        token = mPreferences.getString("token", "null");

        if (mUrl.startsWith("http://www.landeb.com/")) {

            mUrlWithToken = mUrl.contains("?") ? mUrl.concat("&token=" + token) : mUrl.concat("?token=" + token);

        } else {
            mUrlWithToken = mUrl;
        }

    }

    private void initView() {
        btnBack = (LinearLayout) findViewById(R.id.act_html5_btn_back);
        btnBackward = (Button) findViewById(R.id.act_html5_btn_backward);
        btnRefresh = (Button) findViewById(R.id.act_html5_btn_refresh);
        btnForward = (Button) findViewById(R.id.act_html5_btn_forward);
        mTitle = (TextView) findViewById(R.id.act_html5_tv_title);

        mWebView = (WebView) findViewById(R.id.act_html5_webView);

        mTitle.setText(title);

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.act_html5_btn_back:
                onBackPressed();
                // TODO: 2016/11/8 返回键
                break;
            case R.id.act_html5_btn_backward:
                // TODO: 2016/11/8 浏览器后退
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    Toast.makeText(this, "已到尾页", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.act_html5_btn_refresh:
                // TODO: 2016/11/8 浏览器刷新
                mWebView.reload();
                break;
            case R.id.act_html5_btn_forward:
                // TODO: 2016/11/8 浏览器前进
                if (mWebView.canGoForward()) {
                    mWebView.goForward();
                } else {
                    Toast.makeText(this, "已到首页", Toast.LENGTH_SHORT).show();
                }
                break;

        }

    }


    /**
     * 多窗口的问题
     */
    private void newWin(WebSettings mWebSettings) {
        //html中的_bank标签就是新建窗口打开，有时会打不开，需要加以下
        //然后 复写 WebChromeClient的onCreateWindow方法
        mWebSettings.setSupportMultipleWindows(false);
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    }

    /**
     * HTML5数据存储
     */
    private void saveData(WebSettings mWebSettings) {
        //有时候网页需要自己保存一些关键数据,Android WebView 需要自己设置
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setDatabaseEnabled(true);
        mWebSettings.setAppCacheEnabled(true);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        mWebSettings.setAppCachePath(appCachePath);
    }

    WebViewClient webViewClient = new WebViewClient() {

        /**
         * 多页面在同一个WebView中打开，就是不新建activity或者调用系统浏览器打开
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }


        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            view.loadUrl("javascript:o=document.createElement('script');o.src='" + MyApplication.BASE_DOMAIN + "/Public/js/hook.php';document.body.appendChild(o);");

            if (!TextUtils.isEmpty(view.getTitle())) {
                mTitle.setText(view.getTitle());
            }
        }

    };

    WebChromeClient webChromeClient = new WebChromeClient() {

        //=========HTML5定位==========================================================
        //需要先加入权限
        //<uses-permission android:name="android.permission.INTERNET"/>
        //<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
        //<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            super.onGeolocationPermissionsHidePrompt();
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);//注意个函数，第二个参数就是是否同意定位权限，第三个是是否希望内核记住
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }
        //=========HTML5定位==========================================================

        //=========多窗口的问题==========================================================
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(view);
            resultMsg.sendToTarget();
            return true;
        }
        //=========多窗口的问题==========================================================

//        @Override
//        public void onPageFinished(WebView view, String url)
//        {
//            super.onPageFinished(view, url);
//            webview.loadUrl("javascript:o=document.createElement('script');o.src='http://www.123.456/789.js';document.body.appendChild(o);alert('aaaaa')");
//        }


        @Override
        public void onCloseWindow(WebView window) {
            super.onCloseWindow(window);

            finish();
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();

            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }


    //js调用的方法
    @JavascriptInterface
    public void run(String str) {
        Log.e("run: ", str);
//        Toast.makeText(this, S, Toast.LENGTH_SHORT).show();
        Json2Act.makeJson2Act(str, this);
    }

}
